package com.example.controller;

import com.example.config.MyUserDetailsservice;
import com.example.entity.SysUser;
import com.example.rabbitmq.Producer;
import com.example.service.ISysUserService;
import com.example.ulit.JwtUtil;
import com.example.ulit.RabbitMQUtils;
import com.example.ulit.UsrIdByToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2024-09-10
 */
@RestController
@RequestMapping("/uni-app/sys-user")
public class SysUserController {
    @Resource
    ISysUserService sysUserService;
    @Resource
    UsrIdByToken usrIdByToken;

    @Resource
    Producer producer;

    @Resource
    private MyUserDetailsservice myUserDetailsservice;

    @RequestMapping("/login")
    public Object login(@RequestParam("account") String account,@RequestParam("password") String password) {
        SysUser sysUser = sysUserService.searchAllByUsrNameAndUsrPassword(account, password);
        Map<String,Object> hashMap = new HashMap<>();
        if(sysUser != null){
            UserDetails userDetails = myUserDetailsservice.loadUserByUsername(account);
            hashMap.put("token",userDetails.getPassword());
            hashMap.put("code",1);
        }else{
            hashMap.put("code",0);
        }

//        hashMap.put("sysUser",sysUser);
        return hashMap;
//        return sysUserService.searchAllByUsrNameAndUsrPassword(account, password);
    }

    @RequestMapping("/isLogins")
    public Object isLogin(String token){
        return usrIdByToken.getStringRedisTemplate(token);
    }


    @RequestMapping("/isToken")
    public Boolean isToken(@RequestParam("token") String token){
        Map<String, Object> objectMap = JwtUtil.parseToken(token);
        Date expiresAt = (Date) objectMap.get("expiresAt");
        return expiresAt != null && expiresAt.after(new Date());
    }

    @RequestMapping("/insert")
    public Boolean insertUser(String usrName,String usrPassword,String usrEmail,String usrAccount){
        if(sysUserService.insertSysUser(usrName, usrPassword, usrEmail, usrAccount)){
            producer.dispatcher(usrEmail,usrAccount);
            return true;
        }
        return false;
    }

    @RequestMapping("/sendMessage")
    public Object sendMessage(){
        //生成4位随机数
        String code = String.valueOf((int)
                ((Math.random() * 9 + 1) * Math.pow(10, 3)));
        //免费开发测试使用的模板ID为1，具体内容：【云通讯】您的验证码是{1}，请于{2}分钟内正确输入。其中{1}和{2}为短信模板参数。
        return RabbitMQUtils.sendCode("15386355830", code);
    }
    

}
